<!-- 新增/修改弹框 -->
<template>
	<!-- 新增/修改弹窗 -->
	<el-dialog
		v-model="visible"
		width="900px"
		:title="dialogAddOrEdit.title"
		draggable
		@close="closeDialog"
		close-icon="CloseBold"
	>
		<el-form
			ref="addOrEditFormRef"
			:model="formData"
			:rules="rules"
			v-loading="loading"
			label-width="140"
			size=""
			:disabled="dialogAddOrEdit.isLook"
		>
			<el-row justify="start" class="d_left">
				<el-col :span="9">
					<el-form-item label="项目名称" prop="name">
						<el-input v-model="formData.name" placeholder="请输入项目名称"/>
					</el-form-item>
				</el-col>
				
				<el-col :span="9" class="d_left">
					<el-form-item label="施工许可证编号" prop="builderLicenseNum">
						<el-input
							v-model="formData.builderLicenseNum"
							placeholder="请输入施工许可证编号"
						/>
					</el-form-item>
				</el-col>
				
				<el-col :span="9">
					<el-form-item label="行业分类" prop="industryType">
						<el-select
							v-model="formData.industryType"
							placeholder="请选择行业分类"
							clearable
						>
							<el-option
								v-for="item in projectIndustryTypes"
								:key="item.value"
								:label="item.label"
								:value="item.value"
							/>
						</el-select>
					</el-form-item>
				</el-col>
				
				<el-col :span="9" class="d_left">
					<el-form-item label="项目编号" prop="prjNum">
						<el-input v-model="formData.prjNum" placeholder="请输入项目编号"/>
					</el-form-item>
				</el-col>
				
				<el-col :span="9">
					<el-form-item label="项目分类" prop="category">
						<el-select
							v-model="formData.category"
							placeholder="请选择项目类型"
							clearable
						>
							<el-option
								v-for="item in projectCategorys"
								:key="item.value"
								:label="item.label"
								:value="item.value"
							/>
						</el-select>
					</el-form-item>
				</el-col>
				
				<el-col :span="9" class="d_left">
					<el-form-item label="建设单位" prop="buildCorpName">
						<el-select
							v-model="formData.buildCorpName"
							@change="buildCorpChange"
							placeholder="请选择建设单位"
						>
							<el-option v-for="item in constructors" :key="item.value" :label="item.label"
												 :value="item.value"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				
				<el-col :span="9">
					<el-form-item label="建设单位信用代码" prop="buildCorpCode">
						<el-input
							v-model="formData.buildCorpCode"
							readonly
							placeholder="请输入建设单位信用代码"
						/>
					</el-form-item>
				</el-col>
				
				<el-col :span="9" class="d_left">
					<el-form-item label="用地许可证编号" prop="buildPlanNum">
						<el-input
							v-model="formData.buildPlanNum"
							placeholder="请输入用地许可证编号"
						/>
					</el-form-item>
				</el-col>
				
				<el-col :span="9" class="" v-if="dialogAddOrEdit.isLook">
					<el-form-item label="总包企业" prop="lumpContractorCorpName">
						<el-input placeholder="请选择总包企业" v-model="formData.lumpContractorCorpName"></el-input>
					</el-form-item>
				</el-col>
				
				<el-col :span="9" class="d_left" v-if="dialogAddOrEdit.isLook">
					<el-form-item label="监理企业" prop="supervisorCorpName">
						<el-input placeholder="请选择监理企业" v-model="formData.supervisorCorpName"></el-input>
					</el-form-item>
				</el-col>
				
				<el-col :span="9" class="" v-if="dialogAddOrEdit.isLook">
					<el-form-item label="总包企业信用代码" prop="lumpContractorCorpCode">
						<el-input
							v-model="formData.lumpContractorCorpCode"
							placeholder="请输入社会信用代码"
						/>
					</el-form-item>
				</el-col>
				
				<el-col :span="9" class="d_left" v-if="dialogAddOrEdit.isLook">
					<el-form-item label="监理企业信用代码" prop="supervisorCorpCode">
						<el-input
							v-model="formData.supervisorCorpCode"
							placeholder="请输入社会信用代码"
						/>
					</el-form-item>
				</el-col>
				
				<el-col :span="9">
					<el-form-item label="工程许可证编号" prop="prjPlanNum">
						<el-input
							v-model="formData.prjPlanNum"
							placeholder="请输入工程许可证编号"
						/>
					</el-form-item>
				</el-col>
				
				<el-col :span="9" class="d_left">
					<el-form-item label="所在城市" prop="areaCode">
						<el-cascader
							v-model="formData.areaCode"
							placeholder="请选择项目归属地区"
							:options="areaoptions"
							@change="handleCascaderChange"
						/>
					</el-form-item>
				</el-col>
				
				<el-col :span="9">
					<el-form-item label="总投资" prop="invest">
						<el-input
							v-model="formData.invest"
							type="number"
							placeholder="请输入总投资(万元)"
						/>
					</el-form-item>
				</el-col>
				
				<el-col :span="9" class="d_left">
					<el-form-item label="总面积" prop="buildingArea">
						<el-input
							v-model="formData.buildingArea"
							type="number"
							placeholder="请输入总面积(平方米)"
						/>
					</el-form-item>
				</el-col>
				
				<el-col :span="9">
					<el-form-item label="总长度" prop="buildingLength">
						<el-input
							v-model="formData.buildingLength"
							type="number"
							placeholder="请输入总长度(米)"
						/>
					</el-form-item>
				</el-col>
				
				<el-col :span="9" class="d_left">
					<el-form-item label="开工日期" prop="startDate">
						<el-date-picker
							v-model="formData.startDate"
							type="date"
							format="YYYY-MM-DD"
							value-format="YYYY-MM-DD"
							placeholder="选择开工日期"
						/>
					</el-form-item>
				</el-col>
				
				<el-col :span="9">
					<el-form-item label="竣工日期" prop="endDate">
						<el-date-picker
							v-model="formData.endDate"
							type="date"
							format="YYYY-MM-DD"
							value-format="YYYY-MM-DD"
							placeholder="选择竣工日期"
						/>
					</el-form-item>
				</el-col>
				
				<el-col :span="9" class="d_left">
					<el-form-item label="联系人" prop="linkMan">
						<el-input v-model="formData.linkMan" placeholder="请输入联系人"/>
					</el-form-item>
				</el-col>
				
				<el-col :span="9">
					<el-form-item label="联系电话" prop="linkPhone">
						<el-input
							v-model="formData.linkPhone"
							placeholder="请输入联系电话"
						/>
					</el-form-item>
				</el-col>
				
				<el-col :span="9">
					<el-form-item label=""></el-form-item>
				</el-col>
			</el-row>
			
			<el-row justify="start" class="d_left">
				
				<el-button style="margin-left: -10px;position: absolute;top: 0" ref="mapBtnRef" type="success"
									 @click="bmap1VisibleClick" plain>
					<i-ep-mapLocation></i-ep-mapLocation>
					选择定位
				</el-button>
				<el-popover
					placement="top-start"
					:popper-style="{ padding: '0px' }"
					:width="840"
					:visible="bmap1Visible"
					@hide="pupHide"
					@show="pupShow"
					ref="popoverRef"
					:virtual-ref="mapBtnRef"
					virtual-triggering
					trigger="click"
				>
					<projectMap
						ref="bmap1Ref"
						:containSize="{ width: '800px', height: '350px' }"
						:prevPoint="projectPoint"
						:containId="containId1"
						@mapHide="mapHide"
						@sendProjectPoint="sendProjectPoint"
						@sendProjectAddr="sendProjectAddr"
					></projectMap>
				</el-popover>
				
				<el-col :span="9">
					<el-form-item label="经度" prop="lng">
						<el-input
							v-model="formData.lng"
							readonly
							@click="bmap1VisibleClick"
							placeholder="请输入经度"
						/>
					</el-form-item>
				</el-col>
				<el-icon style="margin-left: 340px; position: absolute" color="#409EFC"
				>
					<Promotion
					/>
				</el-icon>
				
				<el-col :span="9" class="d_left">
					<el-form-item label="纬度" prop="lat">
						<el-input
							v-model="formData.lat"
							readonly
							@click="bmap2VisibleClick"
							placeholder="请输入纬度"
						/>
					</el-form-item>
				</el-col>
				<el-icon style="margin-left: 700px; position: absolute" color="#409EFC"
				>
					<Promotion
					/>
				</el-icon>
				
				<el-col :span="21">
					<el-form-item label="项目详细地址" prop="address">
						<el-input
							v-model="formData.address"
							style="width: 100%"
							placeholder="请输入项目详细地址"
						/>
					</el-form-item>
				</el-col>
				
				<el-col :span="21">
					<el-form-item label="项目简介" prop="description">
						<el-input
							v-model="formData.description"
							type="textarea"
							style="width: 100%"
							:row="3"
							placeholder="请输入项目简介"
						/>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		
		<el-timeline>
			<el-timeline-item :timestamp="new Date().toLocaleString()" placement="top">
				<el-card>
					<h4>Update Github template</h4>
					<p>Tom committed 2018/4/12 20:46</p>
				</el-card>
			</el-timeline-item>
			<el-timeline-item :timestamp="new Date().toLocaleString()" placement="top">
				<el-card>
					<h4>Update Github template</h4>
					<p>Tom committed 2018/4/3 20:46</p>
				</el-card>
			</el-timeline-item>
			<el-timeline-item :timestamp="new Date().toLocaleString()" placement="top">
				<el-card>
					<h4>Update Github template</h4>
					<p>Tom committed 2018/4/2 20:46</p>
				</el-card>
			</el-timeline-item>
		</el-timeline>
		
		<template #footer>
			<div class="dialog_footer">
				<el-button type="primary" v-if="!dialogAddOrEdit.isLook" :loading="loading" @click="handleSubmit">{{
						dialogAddOrEdit.footBtn
					}}
				</el-button>
				<el-button @click="closeDialog()">取 消</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup>
import {ref, reactive, nextTick} from "vue";
import projectMap from "../common/projectMap/index.vue";
import {
	bd09togcj02,
	gcj02towgs84,
	wgs84togcj02,
	gcj02tobd09,
} from "@/utils/coordtransform";
import {SocialCreditCodeBlur} from "@/utils/verify";
import {
	new_addProject,
	new_editProject,
	getProjectMagInfo,
} from "@/api/manager/project/index.ts";
import {constructor_pulldown} from '@/api/common/project/index'
import {NewProjectManagerType} from "@/api/manager/project/types";
import {getDicts} from "@/store/modules/dict";
import {loaderMap, scriptNode} from "@/utils/map";

const props = defineProps({
	dialogAddOrEdit: {
		type: Object,
		default: () => ({
			visible: false,
			title: "新增项目",
			footBtn: "新增",
			projectId: 0,
			isLook: false,
		}),
	},
});

const emit = defineEmits(["sendClose"]);

const loading = ref(false);
const constructors = ref();
const projectPoint = ref({lat: 29.641156373429688, lng: 91.13585449304729});
let visible = ref(props.dialogAddOrEdit.visible);
const formData = reactive<NewProjectManagerType>({});
const addOrEditFormRef = ref(ElForm);
const bmap1Ref = ref();
const bmap2Ref = ref();
const bmap1Visible = ref(false);
const bmap2Visible = ref(false);
const isLoaderMap = ref(false);
const containId1 = ref(GenNonDuplicateID());
const mapBtnRef = ref();
const popoverRef = ref();

const rules = reactive<FormRules<NewProjectManagerType>>({
	industryType: [
		{required: true, message: "行业主管部门不能为空", trigger: "blur"},
	],
	name: [{required: true, message: "项目名称不能为空", trigger: "blur"}],
	prjNum: [{required: true, message: "项目编号不能为空", trigger: "blur"}],
	category: [{required: true, message: "项目分类不能为空", trigger: "blur"}],
	buildCorpName: [
		{required: true, message: "建设单位名称不能为空", trigger: "blur"},
	],
	buildCorpCode: [
		{required: true, trigger: "blur", validator: SocialCreditCodeBlur},
	],
	areaCode: [
		{required: true, message: "项目归属地不能为空", trigger: "blur"},
	],
	invest: [{required: true, message: "总投资不能为空", trigger: "blur"}],
	linkMan: [{required: true, message: "联系人姓名不能为空", trigger: "blur"}],
	linkPhone: [
		{required: true, message: "联系人电话不能为空", trigger: "blur"},
		{
			pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
			message: "请输入正确的电话号码",
			trigger: "blur",
		},
	],
	lat: [{required: true, message: "纬度不能为空", trigger: "blur"}],
	lng: [{required: true, message: "经度不能为空", trigger: "blur"}],
	address: [{required: true, message: "项目地点不能为空", trigger: "blur"}],
	propertyNum: [
		{required: true, message: "建设性质分类不能为空", trigger: "blur"},
	],
	functionNum: [
		{required: true, message: "工程用途不能为空", trigger: "blur"},
	],
	fundsSource: [
		{required: true, message: "资金来源不能为空", trigger: "blur"},
	],
});
if (!BMapGL) {
	loaderMap().then((BMap) => {
		if (BMap) {
			isLoaderMap.value = true;
		}
	});
}

onMounted(() => {
	if (props.dialogAddOrEdit.projectId) {
		loading.value = true;
		getProjectMagInfo(props.dialogAddOrEdit.projectId).then(({data}) => {
			Object.assign(formData, data);
			let tempgcj = wgs84togcj02(formData.lng, formData.lat);
			let tempbd = gcj02tobd09(tempgcj[0], tempgcj[1]);
			projectPoint.value = {lat: tempbd[1], lng: tempbd[0]};
			loading.value = false;
		});
	}
});

onUnmounted(() => {
	// bmap1Ref.value.destroyMap();
	// bmap2Ref.value.destroyMap();
	// let tempArr = document.body.children;
	// tempArr = Object.assign([], tempArr);
	// tempArr.map((item) => {
	//   if (item.src && item.src.includes("api.map.baidu.com")) {
	//     item.src.includes("api.map.baidu.com");
	//
	//     document.body.removeChild(item);
	//   }
	//
	//   // if(item.className == 'tangram-suggestion-main'){
	//   //   document.body.removeChild(item);
	//   // }
	// });
	// BMapGL = null;
});

function GenNonDuplicateID() {
	let idStr = Date.now().toString(36);
	idStr += Math.random().toString(36).substr(3);
	return idStr;
}

/* 地图返回事件监听 */
function sendProjectPoint(currentPoint) {
	let tempgcj = bd09togcj02(currentPoint.lng, currentPoint.lat);
	let tempwgs = gcj02towgs84(tempgcj[0], tempgcj[1]);
	projectPoint.value = currentPoint;
	formData.lat = tempwgs[1];
	formData.lng = tempwgs[0];
}

function sendProjectAddr(addr) {
	formData.address = addr;
}

/* 地图隐藏事件 */
function pupHide() {
	if (projectPoint.value) {
	}
	if (bmap1Ref.value) {
		bmap1Ref.value.destroyMap();
	}
	if (bmap2Ref.value) {
		bmap2Ref.value.destroyMap();
	}
}

/* 地图显示事件 */
async function pupShow() {
	if (projectPoint.value) {
		if (
			bmap2Ref.value &&
			bmap2Ref.value.addMarker &&
			bmap2Ref.value.setCenter &&
			bmap2Visible.value
		) {
			await bmap2Ref.value.init();
			await bmap2Ref.value.searchAddress();
			bmap2Ref.value.addMarker(projectPoint.value);
			bmap2Ref.value.setCenter(projectPoint.value);
		}
		if (
			bmap1Ref.value &&
			bmap1Ref.value.addMarker &&
			bmap1Ref.value.setCenter &&
			bmap1Visible.value
		) {
			await bmap1Ref.value.init();
			await bmap1Ref.value.searchAddress();
			bmap1Ref.value.addMarker(projectPoint.value);
			bmap1Ref.value.setCenter(projectPoint.value);
		}
	}
}

function mapHide() {
	bmap1Visible.value = false;
	bmap2Visible.value = false;
}

function bmap2VisibleClick() {
	if (bmap1Visible.value === true) {
		bmap1Visible.value = false;
	}
	bmap2Visible.value = !bmap2Visible.value;
}

function bmap1VisibleClick() {
	if (bmap2Visible.value === true) {
		bmap2Visible.value = false;
	}
	bmap1Visible.value = !bmap1Visible.value;
}

function buildCorpChange(val) {
	let temp = constructors.value.filter(item => item.value === val);
	formData.buildCorpName = temp[0].label;
	formData.buildCorpId = temp[0].value;
	formData.buildCorpCode = temp[0].extend1
}

function sendClose(query) {
	emit("sendClose",query);
}

/**
 * 关闭弹窗
 */
function closeDialog(query) {
	visible.value = false;
	resetForm();
	sendClose(query);
}

/**
 * 重置表单
 */
function resetForm() {
	addOrEditFormRef.value.resetFields();
	addOrEditFormRef.value.clearValidate();
	
	formData.projectId = undefined;
}

//城市联动赋值
const handleCascaderChange = (value: any) => {
	if (value.length == 3) {
		formData.provinceCode = value[0];
		formData.cityCode = value[1];
		formData.areaCode = value[2];
	}
	// 在这里可以对选中的值进行进一步处理
};

/**
 * 项目表单提交
 */
function handleSubmit() {
	addOrEditFormRef.value.validate((valid: any) => {
		if (valid) {
			loading.value = true;
			const projectId = formData.projectId;
			if (projectId) {
				new_editProject(projectId, formData)
					.then((resp) => {
						if (resp.success === true) {
							ElMessage.success(resp.msg);
							closeDialog(true);
						} else {
							ElMessage.warning(resp.msg);
						}
					})
					.finally(() => (loading.value = false));
			} else {
				new_addProject(formData)
					.then((resp) => {
						if (resp.success === true) {
							ElMessage.success(resp.msg);
							closeDialog(true);
						} else {
							ElMessage.warning(resp.msg);
						}
					})
					.finally(() => (loading.value = false));
			}
		}
	});
}

constructor_pulldown().then(data => {
	if (data.success) {
		constructors.value = data.data.list;
	} else {
		ElMessage({
			type: 'error',
			message: data.msg
		})
	}
})

//行政区划
const areaoptions = getDicts("areaTrees").filter(
	(item) => item.value === 540000
);
const projectIndustryTypes = getDicts("projectIndustryTypes"); //项目行业主管部门
const projectCategorys = getDicts("projectCategorys"); //项目分类
</script>

<style lang="scss" scoped>
.d_left {
	margin-left: 60px;
}

:deep(.el-form-item) {
	flex-wrap: wrap;
}

.dialog_footer {
	// display: flex;
	// justify-content: center;
}

:deep(.el-input) {
	width: 200px;
}

:deep(.el-input__inner) {
	// width: 200px;
}

:deep(.el-input__wrapper) {
	width: 200px;
}

:deep(.el-form-item__label) {
	color: #696868;
	font-size: 13px;
}
</style>
